package com.eoner.baselibrary.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.eoner.baselibrary.R;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 *  对 support Design 包中的TabLayout包装
 *  主要实现功能：更改indicator 的长度
 *
 */

public class CommonTabLayout extends FrameLayout {
    private TabLayout mTabLayout;
    private List<String> mTabList;
    private List<View> mCustomViewList;
    private int mSelectIndicatorBg, mIndicatorBg;
    private int mSelectTextColor;
    private int mTextColor;
    private int mIndicatorHeight;
    private int mIndicatorWidth;
    private int mTabMode;
    private int mTextSize;
    private int mTextPadding;
    private int mTextWidth;
    private int tabView;
    private int indicatorPaddingBottom;
    private int selectTextSize;
    private int mTabGravity;
    private static boolean smoothScroll = true;
    public CommonTabLayout(@NonNull Context context) {
        super(context);
        init(context, null);
    }

    public CommonTabLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public CommonTabLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public CommonTabLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs);
    }

    private void readAttr(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CommonTabLayout);
        smoothScroll = typedArray.getBoolean(R.styleable.CommonTabLayout_comSmoothScroll, true);
        mSelectIndicatorBg = typedArray.getResourceId(R.styleable.CommonTabLayout_comTabSelectIndicator, R.color.black);
        mIndicatorBg =typedArray.getResourceId(R.styleable.CommonTabLayout_comTabIndicator, R.color.transparent);
        mTextColor = typedArray.getColor(R.styleable.CommonTabLayout_comTabTextColor, context.getResources().getColor(R.color.black));
        mSelectTextColor = typedArray.getColor(R.styleable.CommonTabLayout_comTabSelectTextColor, context.getResources().getColor(R.color.our_gongzhu_color));
        mIndicatorHeight = typedArray.getDimensionPixelSize(R.styleable.CommonTabLayout_comTabIndicatorHeight, 1);
        mIndicatorWidth = typedArray.getDimensionPixelSize(R.styleable.CommonTabLayout_comTabIndicatorWidth, 0);
        mTextPadding = typedArray.getDimensionPixelSize(R.styleable.CommonTabLayout_comTabTextPadding, 0);
        mTextWidth = typedArray.getDimensionPixelSize(R.styleable.CommonTabLayout_comTabWidth, 0);
        tabView = typedArray.getResourceId(R.styleable.CommonTabLayout_comTabView, R.layout.item_common_tab);
        mTextSize = typedArray.getDimensionPixelSize(R.styleable.CommonTabLayout_comTabTextSize, 14);
        selectTextSize = typedArray.getDimensionPixelSize(R.styleable.CommonTabLayout_comTabSelectTextSize, mTextSize);
        mTabMode = typedArray.getInt(R.styleable.CommonTabLayout_comTabMode, 1);
        indicatorPaddingBottom = typedArray.getDimensionPixelSize(R.styleable.CommonTabLayout_comTabIndicatorPaddingBottom, 0);
        mTabGravity = typedArray.getInt(R.styleable.CommonTabLayout_comTabGravity, 0);
        typedArray.recycle();
    }

    private void init(Context context, AttributeSet attrs) {
        readAttr(context, attrs);

        mTabList = new ArrayList<>();
        mCustomViewList = new ArrayList<>();
        View view = LayoutInflater.from(getContext()).inflate(R.layout.common_tab_layout, this, true);
        mTabLayout = (TabLayout) view.findViewById(R.id.common_tab_view);
        mTabLayout.setTabMode(mTabMode == 1 ? TabLayout.MODE_FIXED : TabLayout.MODE_SCROLLABLE);
        mTabLayout.setTabGravity(mTabGravity);
        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                // onTabItemSelected(tab.getPosition());
                // Tab 选中之后，改变各个Tab的状态
                for (int i = 0; i < mTabLayout.getTabCount(); i++) {
                    View view = mTabLayout.getTabAt(i).getCustomView();
                    if (view == null) {
                        return;
                    }
                    TextView text = (TextView) view.findViewById(R.id.item_common_tab_text);
                    View indicator = view.findViewById(R.id.item_common_tab_indicator);
                    if (i == tab.getPosition()) {
                        text.setTextSize(TypedValue.COMPLEX_UNIT_PX,selectTextSize);
                        text.setTextColor(mSelectTextColor);
                        indicator.setBackgroundResource(mSelectIndicatorBg);
                    } else {
                        text.setTextSize(TypedValue.COMPLEX_UNIT_PX,mTextSize);
                        text.setTextColor(mTextColor);
                        indicator.setBackgroundResource(mIndicatorBg);
                    }
                }

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    public void refreshTab(int index, String tabName, boolean isSelected){
            View view = mTabLayout.getTabAt(index).getCustomView();
            if (view == null) {
                return;
            }
            TextView text = (TextView) view.findViewById(R.id.item_common_tab_text);
            text.setText(tabName);
            mTabLayout.removeTabAt(index);
            mTabLayout.addTab(mTabLayout.newTab().setCustomView(view),index,isSelected);
    }

    public List<View> getCustomViewList() {
        return mCustomViewList;
    }

    public void addOnTabSelectedListener(TabLayout.OnTabSelectedListener onTabSelectedListener) {
        mTabLayout.addOnTabSelectedListener(onTabSelectedListener);
    }

    public void setupWithViewPager(@Nullable ViewPager viewPager) {
        mTabLayout.addOnTabSelectedListener(new ViewPagerOnTabSelectedListener(viewPager, this));
    }

    public TabLayout getTabLayout() {
        return mTabLayout;
    }

    /**
     * 添加tab tabview布局layout的id必须跟默认布局一样
     * @param tab
     */
    public void addTab(String tab,boolean selected) {
        mTabList.add(tab);
        View customView = getTabView(getContext(), tab, mIndicatorWidth, mIndicatorHeight, mTextSize,selected);
        mCustomViewList.add(customView);
        mTabLayout.addTab(mTabLayout.newTab().setCustomView(customView));
    }

    public static class ViewPagerOnTabSelectedListener implements TabLayout.OnTabSelectedListener {

        private final ViewPager mViewPager;
        private final WeakReference<CommonTabLayout> mTabLayoutRef;

        public ViewPagerOnTabSelectedListener(ViewPager viewPager, CommonTabLayout commonTabLayout) {
            mViewPager = viewPager;
            mTabLayoutRef = new WeakReference<CommonTabLayout>(commonTabLayout);
        }

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            mViewPager.setCurrentItem(tab.getPosition(),smoothScroll);
            CommonTabLayout mTabLayout = mTabLayoutRef.get();
            if (mTabLayoutRef != null) {
                List<View> customViewList = mTabLayout.getCustomViewList();
                if (customViewList == null || customViewList.size() == 0) {
                    return;
                }
                for (int i = 0; i < customViewList.size(); i++) {
                    View view = customViewList.get(i);
                    if (view == null) {
                        return;
                    }
                    TextView text = (TextView) view.findViewById(R.id.item_common_tab_text);
                    View indicator = view.findViewById(R.id.item_common_tab_indicator);

                    if (i == tab.getPosition()) {
                        text.setTextSize(TypedValue.COMPLEX_UNIT_PX,mTabLayout.selectTextSize);
                        text.setTextColor(mTabLayout.mSelectTextColor);
                        indicator.setBackgroundResource(mTabLayout.mSelectIndicatorBg);
                    } else {
                        text.setTextSize(TypedValue.COMPLEX_UNIT_PX,mTabLayout.mTextSize);
                        text.setTextColor(mTabLayout.mTextColor);
                        indicator.setBackgroundResource(mTabLayout.mIndicatorBg);
                    }
                }
            }

        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            // No-op
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
            // No-op
        }
    }

    /**
     * 获取Tab 显示的内容
     *
     * @param context
     * @param
     * @return
     */
    public View getTabView(Context context, String text, int indicatorWidth, int indicatorHeight, int textSize,boolean selected) {
        View view = LayoutInflater.from(context).inflate(tabView, null);
        TextView tabText = (TextView) view.findViewById(R.id.item_common_tab_text);
        View indicator = view.findViewById(R.id.item_common_tab_indicator);
        view.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        tabText.setPadding(mTextPadding,0,mTextPadding,0);

        if (mTextWidth>1){
            FrameLayout.LayoutParams layoutParams = (LayoutParams) tabText.getLayoutParams();
            layoutParams.width = mTextWidth;
            tabText.setLayoutParams(layoutParams);
        }
        if (indicatorWidth > 0) {
            FrameLayout.LayoutParams layoutParams = (LayoutParams) indicator.getLayoutParams();
            layoutParams.width = indicatorWidth;
            layoutParams.height = indicatorHeight;
            layoutParams.setMargins(0,0,0,indicatorPaddingBottom);
            indicator.setLayoutParams(layoutParams);
        }
        if(selected){
            tabText.setTextSize(TypedValue.COMPLEX_UNIT_PX,selectTextSize);
            tabText.setTextColor(mSelectTextColor);
            indicator.setBackgroundResource(mSelectIndicatorBg);
        } else {
            tabText.setTextSize(TypedValue.COMPLEX_UNIT_PX,mTextSize);
            tabText.setTextColor(mTextColor);
            indicator.setBackgroundResource(mIndicatorBg);
        }
        tabText.setText(text);
        return view;
    }
}

